package com.lifang.framework.beans.factory.support;

import com.lifang.framework.beans.BeansException;
import com.lifang.framework.beans.factory.config.InstantiationStrategy;

import java.lang.reflect.Constructor;

/**
 * 简单（jdk）反射实例化策略
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiation(BeanDefinition beanDefinition, String beanName, Constructor<?> constructor, Object[] args) {
        Class<?> clazz = beanDefinition.getBeanClass();
        try {
            if (null != constructor) {
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (Exception ex) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", ex);
        }
    }
}
